package web

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func CreatePassword(c *gin.Context) {
	if IsAdminPasswordSet() {
		c.JSON(400, gin.H{"error": "密码已设置"})
		return
	}

	var json struct {
		Password string `json:"password"`
	}
	if err := c.BindJSON(&json); err != nil {
		c.JSON(400, gin.H{"error": "无效的请求"})
		return
	}

	if err := SaveAdminPassword(json.Password); err != nil {
		c.JSON(500, gin.H{"error": "保存密码失败"})
		return
	}

	c.JSON(200, gin.H{"message": "密码设置成功"})
}

func Login(c *gin.Context) {
	var json struct {
		Password string `json:"password"`
	}
	if err := c.BindJSON(&json); err != nil {
		c.JSON(400, gin.H{"error": "无效的请求"})
		return
	}

	if validateAdminPassword(json.Password) {
		session := sessions.Default(c)
		session.Set("authenticated", true)
		session.Save()
		c.JSON(200, gin.H{"redirectTo": "/services"}) // 修改登录成功后的跳转
	} else {
		c.JSON(401, gin.H{"error": "密码错误"})
	}
}

func Logout(c *gin.Context) {
	session := sessions.Default(c)
	session.Clear()
	session.Save()
	c.JSON(200, gin.H{"message": "已登出"})
}
